import * as R from 'ramda';

import { Button, Modal, Popconfirm, Space, message } from 'antd';
import React, { useMemo, useRef } from 'react';
import {
  authorization,
  createRole,
  deleteRole,
  getRoleDetail,
  getRoleList,
  updateRole,
} from '../../../service/role';
import { paginationWrapper, unResWrapper } from '../../../utils/common';

import AuthButton from '../../../containers/AuthButton';
import Authorization from './components/Authorization';
import { ButtonEnum } from '../../../lib/enums';
import ConfirmButton from '../../../components/ConfirmButton';
import ProTable from '@ant-design/pro-table';
import RoleForm from './components/RoleForm';
import { useButtonPermission } from '../../../hooks/permissions';
import useCRUD from '../../../hooks/useCRUD';
import { useFloatLayer } from '@r-magician/hooks';
import { useRequest } from 'ahooks';
import variables from '../../../lib/themeVariables';

const RoleManage = () => {
  const {
    isEdit,
    form,
    openHandle,
    visible,
    confirmLoading,
    okHandle,
    close,
    removeHandle,
    removeLoading,
    fetchList,
    actionRef,
    fetchDetail,
    editData,
  } = useCRUD({
    listService: paginationWrapper(getRoleList),
    createService: unResWrapper(createRole),
    updateService: unResWrapper(({ id, ...data }) => updateRole(id, data)),
    getService: unResWrapper(R.compose(getRoleDetail, R.prop('id'))),
    deleteService: unResWrapper(deleteRole),
    messages: {
      create: '创建角色成功',
      update: '更新角色成功',
      remove: '删除角色成功',
    },
  });

  const title = useMemo(() => (isEdit ? '编辑角色' : '创建角色'), [isEdit]);
  const authorizationRef = useRef(null);
  const { run: submit } = useRequest(
    () => {
      return authorization(editData.id, authorizationRef.current?.getData());
    },
    {
      manual: true,
    },
  );
  const authorizationFl = useFloatLayer({
    onConfirm: async () => {
      try {
        await submit();
        message.success('操作成功');
        actionRef.current?.reload();
        return true;
      } catch (e) {
        return false;
      }
    },
  });

  const { hasRemoveRoleAuthority } = useButtonPermission();

  const columns = [
    { title: '角色名称', dataIndex: 'name' },
    { title: '角色编码', dataIndex: 'code' },
    { title: '角色描述', dataIndex: 'description', search: false },
    {
      title: '绑定菜单数',
      dataIndex: 'menuList',
      search: false,
      render: R.length,
    },
    {
      title: '绑定用户数',
      dataIndex: 'userList',
      search: false,
      render: R.length,
    },
    {
      title: '操作',
      search: false,
      width: 200,
      fixed: 'right',
      render: (_, row) => {
        return (
          <Space>
            <AuthButton
              code={ButtonEnum.UPDATE_ROLE}
              size="small"
              type="link"
              onClick={() => openHandle(row)}
            >
              编辑
            </AuthButton>
            <AuthButton
              code={ButtonEnum.ROLE_AUTHORIZATION}
              size="small"
              type="link"
              onClick={async () => {
                await fetchDetail(row);
                authorizationFl.open();
              }}
            >
              授权
            </AuthButton>
            {hasRemoveRoleAuthority && (
              <ConfirmButton
                confirmProps={{
                  title: `确定删除角色【${row.name}】?`,
                }}
                text="删除"
                buttonProps={{
                  size: 'small',
                  type: 'text',
                  danger: true,
                }}
                service={() => removeHandle(row)}
              />
            )}
          </Space>
        );
      },
    },
  ];

  return (
    <div style={{ margin: variables.space }}>
      <Modal
        visible={visible}
        width="70%"
        onOk={okHandle}
        confirmLoading={confirmLoading}
        onCancel={close}
        title={title}
        destroyOnClose
      >
        <RoleForm form={form} editable={isEdit} />
      </Modal>
      <Modal
        width="70%"
        visible={authorizationFl.visible}
        confirmLoading={authorizationFl.confirmLoading}
        onCancel={authorizationFl.close}
        onOk={authorizationFl.okHandle}
        destroyOnClose
        title={`授权:【${editData?.name}】`}
      >
        <Authorization ref={authorizationRef} role={editData} />
      </Modal>
      <ProTable
        actionRef={actionRef}
        request={(...args) => fetchList(...args)}
        rowKey="id"
        columns={columns}
        toolBarRender={() => [
          <AuthButton
            code={ButtonEnum.CREATE_ROLE}
            key="create"
            type="primary"
            onClick={() => openHandle()}
          >
            创建角色
          </AuthButton>,
        ]}
      />
    </div>
  );
};

export default RoleManage;
